package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;
import com.itheima.edu.info.manager.domain.Teacher;

/**
 * @Author 王加鑫
 * @Date 2021/5/4 20:40
 * @Version 1.0
 */
public class StudentDao {
    //定义一个全局Student类型的数组来接收
    private  Student[] students = new Student[5];

    /*
    dao层添加学生
     */
    public boolean addStudent(Student student) {
        //标记位思想:假设数组已经满了
        int index = -1;
        for (int i = 0; i < students.length; i++) {
            //如果数组还有元素为null值时,那么index等于该索引
            if(students[i] == null){
                index = i;
                //break是防止将数组中其他null值也改变了
                break;
            }
        }
        if(index == -1){
            return false;
        }else {
            students[index] = student;
            return true;
        }
    }

    /*
    dao层查询全部学生信息
     */
    public Student[] findAllStudent() {
        return students;
    }

    /*
    根据service传过来的下标来删除元素
     */
    public void deleteStudent(String sid) {
        //根据学号查找到指定索引
        int index = getIndex(sid);
        students[index] = null;
    }

    /*
    根据索引查找单个Student对象
     */
    public Student selectStudentByIndex(int index) {
        if(index != -1){
            return students[index];
        }
        return null;

    }

    /*
    根据学号获取索引
     */
    public int getIndex(String sid){
        //标记位思想:默认认为数组没有重复sId,flag为false
        int index = -1;
        for (int i = 0; i < students.length; i++) {
            //当数组元素不为空且取出来的值等于传过来的sId值时,说明id重复
            if(students[i] != null && students[i].getId().equals(sid)){
                index = i;
            }
        }
        return index;
    }

    /*
    dao层修改学生
     */
    public void updateStudent(String sId, Student student) {
        //根据学号找到索引
        int index = getIndex(sId);
        students[index] = student;

    }
}
